//
//  PaiGoodDetailViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/2/6.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PaiGoodDetailViewController.h"
#import "PurchaseViewController.h"
#import "YXCustomActionSheet.h"
#import "DyShare.h"
#import "SocketRocket.h"

@interface PaiGoodDetailViewController () <UIWebViewDelegate, YXCustomActionSheetDelegate, SRWebSocketDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIView *bottombar;
@property (strong,nonatomic) UITextField *addprice;
@property (strong, nonatomic) UILabel *nowprice;
@property (strong, nonatomic) NSString *nowpricevalue;

@property (strong, nonatomic) NSString *url;
@property (strong, nonatomic) UIImage *shareImg;

@property (strong, nonatomic) SRWebSocket *socket;

@end

@implementation PaiGoodDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBack:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.frame = CGRectMake(0, 0, 26, 20);
    [buttonShare setBackgroundImage:[UIImage imageNamed:@"goodshare"] forState:UIControlStateNormal];
    UIBarButtonItem *btnShare = [[UIBarButtonItem alloc]initWithCustomView:buttonShare];
    [buttonShare addTarget:self action:@selector(clickShare:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnShare;
    
    [self makeBottomBar];
    
    //NSString *url = [NSString stringWithFormat:@"http://192.168.1.11:8080/auctionWebSocket/%@", self.productId];
    NSString *url = [NSString stringWithFormat:@"wss://app.zallhy.com/auctionWebSocket/%@", self.productId];
    self.socket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    self.socket.delegate = self;    // 实现这个 SRWebSocketDelegate 协议啊
    [self.socket open];
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    NSLog(@"连接成功，可以立刻登录你公司后台的服务器了，还有开启心跳");
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"连接失败，这里可以实现掉线自动重连，要注意以下几点");
    NSLog(@"1.判断当前网络环境，如果断网了就不要连了，等待网络到来，在发起重连");
    NSLog(@"2.判断调用层是否需要连接，例如用户都没在聊天界面，连接上去浪费流量");
    NSLog(@"3.连接次数限制，如果连接失败了，重试10次左右就可以了，不然就死循环了。或者每隔1，2，4，8，10，10秒重连...f(x) = f(x-1) * 2, (x=5)");
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"连接断开，清空socket对象，清空该清空的东西，还有关闭心跳！");
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message  {
    //DYLog(@"receive:%@", message);
    //{"auctionLogList":[{"bid_price":600.0,"serial_no":834660887487135744,"user_id":821981235280334848,"bid_tm":"2017-02-23 15:07:17","goods_id":834660650093723648,"user_name":"123456"}],"auctionMaxPrice":"600"}
    NSString *str = message;
    NSDictionary *dict = [self dictionaryWithJsonString:str];
    DYLog(@"receive dict:%@", dict.description);
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"updatedAuctionInfo(\'%@\')", str]];
    NSArray *array = [dict objectForKey:@"auctionLogList"];
    if (array && array.count > 0) {
        NSDictionary *onedict = array[0];
        self.nowpricevalue = [onedict objectForKey:@"bid_price"];
        self.nowprice.text = [NSString stringWithFormat:@"当前价：¥%@", self.nowpricevalue];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.socket close];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationWhite:self];
    
    self.nowpricevalue = self.gooddata.last_auction_price;
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:self.goodname WithTextColor:[UIColor blackColor]];
    self.url = [NSString stringWithFormat:@"https://app.zallhy.com/h5/mobile/#/auction_detail/%@/%@", self.productId, [UserData usertoken]];

    self.webView.delegate = self;
    [self.webView setUserInteractionEnabled:YES];//是否支持交互
    [self.webView setScalesPageToFit:YES];//自动缩放以适应屏幕
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
    [self downloadShareImage];
}

- (void)makeBottomBar {
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = LineColor;
    [self.bottombar addSubview:line];
    
    self.nowprice = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 110, 30)];
    self.nowprice.text = [NSString stringWithFormat:@"当前价：¥%@", self.gooddata.last_auction_price];
    self.nowprice.font = [UIFont systemFontOfSize:14];
    [self.bottombar addSubview:self.nowprice];
    
    self.addprice =  [[UITextField alloc] initWithFrame:CGRectMake(120, 10, ScreenWidth - 10 - 80 - 10 - 30 - 120 - 10, 30)];
    _addprice.placeholder = [NSString stringWithFormat:@"最低%@", self.gooddata.step_price];
    _addprice.textAlignment = NSTextAlignmentCenter;
    _addprice.font = [UIFont systemFontOfSize:12];
    _addprice.keyboardType = UIKeyboardTypeNumberPad;
    //_addprice.delegate = self;
    [self.bottombar addSubview:_addprice];
    [self.addprice.layer setBorderWidth:1];
    _addprice.layer.masksToBounds = YES;
    _addprice.layer.cornerRadius = 2.f;
    if (![[DeviceHelper getPhoneType] isEqualToString:@"iPhone5_5S"]) {
        _addprice.placeholder = [NSString stringWithFormat:@"最低加价%@元", self.gooddata.step_price];
        _addprice.font = [UIFont systemFontOfSize:14];
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace, (CGFloat[]){0.8, 0.8, 0.8, 1});
    [self.addprice.layer setBorderColor:colorref];
    CGColorRelease(colorref);
    CGColorSpaceRelease(colorSpace);
    
    UIButton *buttonQ = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonQ.frame = CGRectMake(ScreenWidth - 10 - 80 - 10 - 30, 10, 30, 30);
    [buttonQ setTitle:@"+" forState:UIControlStateNormal];
    buttonQ.titleLabel.font = [UIFont systemFontOfSize:20];
    [buttonQ setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    buttonQ.backgroundColor = LineColor;
    [self.bottombar addSubview:buttonQ];
    [buttonQ addTarget:self action:@selector(clickAdd:) forControlEvents:UIControlEventTouchUpInside];
    buttonQ.layer.masksToBounds = YES;
    buttonQ.layer.cornerRadius = 2.f;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ScreenWidth - 10 - 80, 10, 80, 30);
    [button setTitle:@"出价" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blackColor];
    [self.bottombar addSubview:button];
    [button addTarget:self action:@selector(clickGivePrice:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 2.f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goPop {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickCol:(UIButton *)button {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/userCenter/ScProduct?goods_id=%@", APIYIGOU, self.productId];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [ViewFactory showSuccess:[dict objectForKey:@"message"]];
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)clickAdd:(UIButton *)button {
    NSString *base = self.gooddata.step_price;
    
    if (self.addprice.text.length == 0) {
        NSInteger nowprice = [self.nowpricevalue integerValue];
        nowprice += [base integerValue];
        self.addprice.text = [NSString stringWithFormat:@"%ld", (long)nowprice];
    } else {
        NSInteger former = [self.addprice.text integerValue];
        NSInteger now = former + [base integerValue];
        self.addprice.text = [NSString stringWithFormat:@"%ld", (long)now];
    }
}

- (void)clickGivePrice:(UIButton *)button {
    NSInteger former = 0;
    if (self.addprice.text.length > 0) {
        former = [self.addprice.text integerValue] - [self.nowpricevalue integerValue];
    }
    if (former < [self.gooddata.step_price integerValue]) {
        [ViewFactory showInfoMsg:@"低于最低出价幅度！"];
        return;
    }
    
    NSInteger finalprice = former + [self.nowpricevalue integerValue];
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/order/paimaiPrice?product_id=%@&price=%ld", APIYIGOU, self.productId, finalprice];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"出价成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"出价失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)clickReport {
    DYBaseRequest *request = [DYBaseRequest new];
    //NSString *status = @"01";
    //report_obj举报对象，00：话题，01：文章，03：直播，04：商品
    //report_type举报类型,00：色情，01：反动，02：虚假，99：其他
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addReport?report_obj=%@&report_obj_id=%@&report_type=%@&report_content=%@", APIYIGOU, @"04", self.productId, @"00", @""];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"举报成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"举报失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)downloadShareImage {
    NSString *imgurl = @"";
    imgurl = self.gooddata.goods_pic_url;
    NSArray *array = [self.gooddata.goods_pic_url componentsSeparatedByString:@","];
    if (array.count > 0) {
        imgurl = array[0];
    }
    if (!self.shareImg) {
        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:imgurl] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            self.shareImg = image;
        }];
    }
}

- (void)clickShare:(UIButton *)button {
    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
    cusSheet.delegate = self;
    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
                              @{@"name":@"微信",@"icon":@"sns_wx"},
                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},
                              @{@"name":@"举报 ",@"icon":@"sns_jb"}];
    
    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
}

- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;
    
    DyShareType type;
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        case 5: {
            [self clickReport];
            return;
        }
        default:
            break;
    }
    [[DyShare getInstance]shareWithShareType:type Content:@"" title:self.gooddata.goods_name url:self.url image:self.shareImg delegate:nil];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [ViewFactory showLoadingEnableTouch];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //    NSString *script = [NSString stringWithFormat:
    //                        @"var script = document.createElement('script');"
    //                        "script.type = 'text/javascript';"
    //                        "script.text = \"function ResizeImages() { "
    //                        "var img;"
    //                        "var maxwidth=%f;"
    //                        "for(i=0;i <document.images.length;i++){"
    //                        "img = document.images[i];"
    //                        "if(img.width > maxwidth){"
    //                        "img.width = maxwidth;"
    //                        "}"
    //                        "}"
    //                        "}\";"
    //                        "document.getElementsByTagName('head')[0].appendChild(script);", ScreenWidth - 20];
    //    [webView stringByEvaluatingJavaScriptFromString: script];
    //    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    [ViewFactory dismissLoading];
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    DYLog(@"title:%@", title);
}

- (void)test {
    [self.webView stringByEvaluatingJavaScriptFromString:@"updatedAuctionInfo('1')"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (error) {
        NSDictionary *userinfo = error.userInfo;
        if (userinfo) {
            NSString *url = [userinfo objectForKey:@"NSErrorFailingURLStringKey"];
            if([url hasPrefix:@"rrcc://"]) {
                return;
            }
        }
    }
    [ViewFactory showErrorStrMsg:@"加载失败！"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}

@end
